package com.woniuxy.lrz.carlproject.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.lrz.carlproject.controller.form.userform.AddShopcarForm;
import com.woniuxy.lrz.carlproject.controller.form.userform.ChangeShopcarForm;
import com.woniuxy.lrz.carlproject.model.Shopcar;
import com.woniuxy.lrz.carlproject.dao.ShopcarMapper;
import com.woniuxy.lrz.carlproject.service.ShopcarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author lrz
 * @since 2022-10-04
 */
@Service
public class ShopcarServiceImpl extends ServiceImpl<ShopcarMapper, Shopcar> implements ShopcarService {
    @Resource
    private ShopcarMapper shopcarMapper;
    //新增购物车
    public void addShopcar(AddShopcarForm addShopcarForm) {
        //判断是否存在
        boolean flag = true;
        List<Shopcar> shopcar1 = getShopcar();
        for(Shopcar s : shopcar1){
            if(s.getGoodSkuId() == addShopcarForm.getGoodSkuId()){
                //增加购物车数量
                s.setGoodCount(s.getGoodCount()+ addShopcarForm.getGoodCount());
                int i = shopcarMapper.updateById(s);
                flag = false;
            }
        }
        if(!flag) return;
        Shopcar shopcar = BeanUtil.copyProperties(addShopcarForm, Shopcar.class);
        shopcar.setUserId(Integer.parseInt((String) StpUtil.getLoginId()));
        int insert = shopcarMapper.insert(shopcar);
    }

    //获取购物车信息
    public List<Shopcar> getShopcar() {
        QueryWrapper<Shopcar> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",Integer.parseInt((String) StpUtil.getLoginId()));
        List<Shopcar> shopcars = shopcarMapper.selectList(wrapper);
        return shopcars;
    }

    //修改购物车商品数量
    public void changeNum(ChangeShopcarForm changeShopcarForm) {
        Shopcar shopcar = new Shopcar();
        shopcar.setShopcarId(changeShopcarForm.getShopcarId());
        shopcar.setGoodCount(changeShopcarForm.getGoodCount());
        int i = shopcarMapper.updateById(shopcar);
    }

    //移除购物车
    public void deleteGood(Integer shopcarId) {
        int i = shopcarMapper.deleteById(shopcarId);
    }
}
